<?php

namespace App\Dao;

use App\Model\OliModel;
use Illuminate\Support\Facades\DB;

class OlisDao extends BaseDao
{
    public static function builder_query($params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = OliModel::query();
        $query->when(checkIsHasField($params,'oli_id'),function ($query)use ($params){
            $query->where('oli_id',$params['oli_id']);
        });

        $query->when(checkIsHasField($params,'status'),function ($query)use ($params){
            $query->where('status',$params['status']);
        });

        return $query;
    }

    public static function pageinate($params = []): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        return self::builder_query($params)->paginate();
    }


    public static function add($params = [])
    {
        checkForData(
            ['oli_title','price'],
            ['请输入标题','请添加价格'],
            $params
        );
        if(self::builder_query()->create($params) === false){
            self::error('添加失败');
        }
    }

    public static function edit(array $params)
    {
        if (self::builder_query(['oli_id'=>self::deleteParamId($params,'oli_id')])->update(self::filterFields($params,new OliModel())) === false){
            self::error('修改失败');
        }
    }

    public static function info(array $all)
    {
        return self::builder_query($all)->first();
    }

    public static function olis(array $params = [])
    {
        return self::builder_query($params)->orderByDesc('created_at')->get();
    }

    public static function send_oli(array $params)
    {
        checkForData(
            ['phone','oli_num'],
            ['请输入手机号','请输入数量'],
            $params
        );


        $user_query = UsersDao::builder_query([
            'user_id'=>$params['user_id']
        ]);
        if(!$user_query->exists()){
            self::error('失败');
        }
        $user_info = $user_query->first()->toArray();
        if($user_info['oli_nums'] < $params['oli_num']){
            self::error('用户桶数不足');
        }
        $be_query = UsersDao::builder_query([
            'phone'=>$params['phone']
        ]);
        if(!$be_query->exists()){
            self::error('手机号不存在');
        }
        $beInfo = $be_query->first()->toArray();
        //桶数足够
        DB::beginTransaction();
        try {
            OliBillsDao::oli_nums_update($beInfo['user_id'],$params['oli_num'],'获得赠送能源');
            OliBillsDao::oli_nums_update($params['user_id'],-($params['oli_num']),'赠送能源扣除');
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }
}
